<template>
	<conf-module-container ref="refConfModuleContainer" class="alarm-notification-form-container">
		<template #Slot-Conf-Module-Header>
			<global-svg-icon
				icon-name="return"
				width="18px"
				height="18px"
				class="header-icon"
				style="margin-right: 8px; cursor: pointer"
				@click="router.go(-1)"
			></global-svg-icon>
			<p class="font-20-bold bread-crumb-title" style="color: #f0f6fc">
				{{ !route.query.id ? '新增' : '编辑' }}
			</p>
		</template>

		<template #Slot-Conf-Module-Content>
			<div style="display: flex">
				<div class="the-alarm-notice-config">
					<div class="font-16-bold the-common-title">
						<global-svg-icon icon-name="config-title-tri" width="3px" height="18px" style="margin-right: 16px"></global-svg-icon>
						<div>{{ !route.query.id ? '新增报警通知' : '编辑报警通知' }}</div>
					</div>
					<div class="the-alarm-notice-form">
						<a-spin :spinning="formLoading">
							<a-form ref="formRef" :model="formData" name="alarm-notice" layout="vertical" :rules="addRules">
								<a-form-item name="name" label="配置名称" style="margin-top: -32px">
									<a-input v-model:value="formData.name" :maxlength="10" placeholder="请输入" style="width: 320px"></a-input>
								</a-form-item>

								<a-form-item label="报警类型" name="type">
									<a-radio-group v-model:value="formData.type" @change="changeAlarmType">
										<a-radio :value="1">硬件报警</a-radio>
										<a-radio :value="0">算法报警</a-radio>
									</a-radio-group>
								</a-form-item>

								<a-form-item name="areaItem" label="所属车间">
									<a-select
										v-model:value="formData.areaItem"
										label-in-value
										style="width: 412px"
										placeholder="请选择"
										:options="areaOpts"
										@change="
											() => {
												formData.aiIdList = [];
												getAIServiceList();
											}
										"
									></a-select>
								</a-form-item>

								<a-form-item v-if="formData.type === 0" name="aiIdList" label="报警算法">
									<a-select
										v-model:value="formData.aiIdList"
										:disabled="!formData.areaItem"
										style="width: 412px"
										placeholder="请选择"
										:options="AIServiceList"
										mode="multiple"
										max-tag-count="responsive"
										@change="changeAIService"
									></a-select>
								</a-form-item>

								<a-form-item v-else name="alarmTypeList" label="报警指标">
									<a-checkbox-group v-model:value="formData.alarmTypeList" :options="alarmOptions"></a-checkbox-group>
								</a-form-item>

								<!-- <a-form-item v-if="formData.type === 0" name="deviceIdList" label="报警设备">
									<a-cascader
										v-model:value="formData.deviceList"
										style="width: 412px"
										class="select-item"
										:loading="cameraListLoading"
										max-tag-count="responsive"
										multiple
										:options="boxDeviceList"
										:field-names="{
											label: 'label',
											value: 'id',
											children: 'children'
										}"
										expand-trigger="hover"
										placeholder="请选择"
										allow-clear
										show-arrow
										@change="changeBoxSerialList"
									>
										<template #label="data">
											{{ data }}
										</template>
									</a-cascader>
								</a-form-item> -->

								<a-form-item v-if="formData.type === 1" name="boxSerialList" label="报警设备">
									<!-- 选择框   硬件报警 -->
									<a-select
										v-model:value="formData.boxSerialList"
										style="width: 412px"
										placeholder="请选择"
										:options="BelongingBoxList"
										max-tag-count="responsive"
										mode="multiple"
										@change="changeBoxSerial"
									></a-select>
								</a-form-item>

								<a-form-item name="notifyTypeStr" label="通知方式">
									<a-checkbox :checked="formData.notifyTypeStr === '1'" disabled><span style="color: #b0b5c0">公众号</span></a-checkbox>
								</a-form-item>

								<a-form-item name="通知人" label="通知人">
									<a-select
										v-model:value="formData.personIdList"
										mode="multiple"
										show-search
										style="width: 100%"
										placeholder="请选择"
										allow-clear
										:options="personList"
										:filter-option="false"
										@search="getPersonList"
									>
										<template #notFoundContent v-if="personLoading">
											<a-spin size="small"></a-spin>
										</template>
									</a-select>
								</a-form-item>

								<!-- <a-form-item label="通知人" name="notifyPersonList">
									<a-space :key="user.id" v-for="(user, index) in formData.notifyPersonList">
										<a-form-item
											:name="['notifyPersonList', index, 'userName']"
											:rules="{
												required: true,
												message: '请输入通知人'
											}"
										>
											<a-input v-model:value="user.userName" placeholder="姓名" style="width: 156px; height: 36px" :maxlength="10">
												<template #prefix>
													<global-svg-icon icon-name="user-line" width="18px" height="18px"></global-svg-icon>
												</template>
											</a-input>
										</a-form-item>
										<a-form-item
											:name="['notifyPersonList', index, 'phone']"
											:rules="{
												required: true,
												validator: g6RegValidate.checkPhone
											}"
										>
											<a-input v-model:value="user.phone" placeholder="手机号" style="width: 220px; height: 36px" :maxlength="11">
												<template #prefix> <global-svg-icon icon-name="phone" width="18px" height="18px"></global-svg-icon> </template
											></a-input>
										</a-form-item>
										<span
											v-if="formData.notifyPersonList.length !== 1"
											class="iconfont icon-close-circle-fill"
											@click="removeUser(user, index)"
										></span>
									</a-space>
									<a-form-item>
										<div type="dashed" block class="addBtn" @click="addUser">
											<plus-outlined></plus-outlined>
											添加
										</div>
									</a-form-item>
								</a-form-item> -->

								<a-form-item style="margin-top: 32px">
									<a-button type="primary" html-type="submit" class="form-button" :loading="loading" @click="addDeviceSubmit"
										>确定</a-button
									>
									<a-button @click="cancelModal">取消</a-button>
								</a-form-item>
							</a-form>
						</a-spin>
					</div>
				</div>
			</div>
		</template>
	</conf-module-container>
</template>

<script setup lang="ts" name="alarm-notices-form">
// import { g6RegValidate } from 'glasssix-utils-ts';
// import { PlusOutlined } from '@ant-design/icons-vue';
import { VerifyForm } from '@/global-utils/check';
import { Rule } from 'ant-design-vue/es/form';
import httpServe from '@/global-services';
import { AlarmNoticeAPI, CameraManagementAPI } from '../../api';
import { TsSelectOptItem } from '../../type';
import { ConfModuleContainer } from '../../components/index';
const route = useRoute();
const router = useRouter();
const editId = route.query.id as string;
const formRef = ref();
const loading = ref<boolean>(false);
const $message: any = inject('$message');
// 表单数据
const formLoading = ref<boolean>(false);

let formData = reactive<any>({
	name: '',
	type: 0,
	aiIdList: [],
	alarmTypeList: [],
	notifyTypeStr: '1', // 0 - 短信，1 - 公众号
	deviceIdList: [],
	boxSerialList: undefined,
	notifyPersonList: [],
	personIdList: [],
	areaItem: undefined
});
const areaOpts = ref<any[]>([]);
const getAllRegions = async () => {
	areaOpts.value = [];
	const res: any = await httpServe.getHttp('/base/mirgic/box/monitor/getDeviceList')();
	if (res.code === 0) {
		areaOpts.value = res.data.map((i: any) => {
			return { label: i.name, value: i.id };
		});
	}
};

// RTSP正则
const addRules: Record<string, Rule[]> = {
	name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
	type: [{ required: true, message: '请输入报警类型', trigger: 'change' }],
	aiIdList: [{ required: true, message: '请选择报警算法', trigger: 'blur' }],
	alarmTypeList: [{ required: true, message: '请选择报警指标', trigger: 'blur' }],
	deviceIdList: [{ required: true, message: '请选择报警设备', trigger: 'blur' }],
	boxSerialList: [{ required: true, message: '请选择报警设备', trigger: 'blur' }],
	notifyPersonList: [{ required: true, message: '请输入通知人', trigger: 'blur' }],
	areaItem: [{ required: true, message: '请选择所属车间', trigger: 'blur' }]
};

// 通知人员
const personLoading = ref(false);
const personList = ref<any[]>([]);
const getPersonList = async (searchVal: any) => {
	personList.value = [];
	personLoading.value = true;
	const res: any = await httpServe.getHttp('/base/zelo/user/list')(!searchVal ? {} : { name: searchVal });
	if (res.code === 0) {
		personList.value = res.data.map((i: any) => {
			return { label: `${i.name}(${i.phone})`, value: i.id };
		});
	}
	personLoading.value = false;
};

/* ------------------- 处理筛选区域的多选框逻辑 ------------------ */

// AI服务下拉数据
const AIServiceList = ref<TsSelectOptItem[]>([]);
const getAIServiceList = async (): Promise<void> => {
	// let { data } = await AlarmNoticeAPI.AIServiceList();
	// AIServiceList.value = data;
	AIServiceList.value = [];
	const res: TsRes = await httpServe.getHttp(`/base/bAiService/areaId?areaId=${formData.areaItem.value}`)();
	if (res.code === 0) {
		AIServiceList.value = res.data.map((i: any) => {
			return { label: i.aiSrvName, value: i.aiSrvType };
		});
	}
};
// 所属盒子boxDeviceId
const BelongingBoxList = ref<any>([]);
const getDeviceAreaList = async (): Promise<void> => {
	BelongingBoxList.value = [];
	let res: TsRes = await CameraManagementAPI.DeviceAreaList();
	res.data.forEach((item: any) => {
		BelongingBoxList.value.push({ value: item.serial, label: item.boxName });
	});
};
const changeBoxSerial = (val: any): void => {
	// searchQuery.value.boxSerial = val;
	console.log(val);
};
const changeAIService = (val: any): void => {
	console.log(val);
};
// 切换算法配置
const changeAlarmType = (): void => {
	formData.aiIdList = formData.aiIdList === null ? [] : formData.aiIdList;

	//
};

// 盒子/摄像头下拉数据
// 回显页面的
// const cameraListLoading = ref<boolean>(false);

// 下拉数据
const boxDeviceList = ref<any>([]);
const getBoxDeviceList = async (): Promise<void> => {
	let { data } = await AlarmNoticeAPI.boxDeviceList();
	boxDeviceList.value = data;
};
/* ---------------处理盒子/摄像头----------------- */
const deviceIdList = ref<any[]>([]);
// 递归筛选
// const findObjectById = (data: any, id: string): any => {
// 	for (let i = 0; i < data.length; i++) {
// 		const obj = data[i];

// 		if (obj.id === id) {
// 			return obj;
// 		}
// 		if (obj.children && obj.children.length > 0) {
// 			const result = findObjectById(obj.children, id);
// 			if (result) {
// 				return result;
// 			}
// 		}
// 	}
// 	return null;
// };
// 处理盒子/摄像头
// const changeBoxSerialList = (value: any): void => {
// 	formData.deviceIdList = [];
// 	value.forEach((item: any) => {
// 		const re = findObjectById(boxDeviceList.value, item[item.length - 1]);

// 		// 选中盒子时将所有子项的deviceId获取到
// 		if (re.children) {
// 			re.children.forEach((itemChild: any) => {
// 				formData.deviceIdList.push(itemChild.deviceId as never);
// 			});
// 		} else {
// 			// 选中子项时直接把deviceId获取到
// 			formData.deviceIdList.push(re.deviceId as never);
// 		}
// 	});
// };

const alarmOptions = [
	{ label: '存储空间', value: 1 },
	{ label: 'CPU利用率', value: 2 },
	{ label: 'NPU利用率', value: 3 },
	{ label: '内存利用率', value: 4 }
];

// ======================================================================

const cancelModal = (): void => {
	router.go(-1);
};
// 添加
const addDeviceSubmit = (): void => {
	VerifyForm(formRef, async () => {
		let newForm = JSON.parse(JSON.stringify(formData));
		newForm.areaName = formData.areaItem.label;
		newForm.areaId = formData.areaItem.value;
		delete newForm.areaItem;

		loading.value = true;
		try {
			// 接口
			let res: TsRes = !editId ? await AlarmNoticeAPI.addNotice(newForm) : await AlarmNoticeAPI.editNotice(newForm);
			if (res.code === 0) {
				$message.success('保存成功');
				router.go(-1);
			}
		} finally {
			loading.value = false;
		}
	});
};

const delNoArray = (treeData: any, deviceId: any): any => {
	const newList = [...new Set(deviceId.flat())];
	let deviceIds = deviceId;
	console.log(newList, '处理后的====传入数据');

	// 删除不存在的id数组
	const delNotIdArry = (): any => {
		newList.forEach((key) => {
			if (getTreeById(treeData, key)) {
				let delKey = getTreeById(treeData, key);
				// console.log(delKey, '=====================delKey11');

				let del = deviceIds.findIndex((item: any) => item[0] === delKey || item[1] === delKey);
				deviceIds.splice(del, 1);
				// console.log(deviceIds, '删除后');
			}
		});
		return deviceIds;
	};

	const getTreeById = (treeData: any, key: any): any => {
		for (let i = 0; i < treeData.length; i++) {
			// console.log('比较', treeData[i].id, key);

			if (treeData[i].id === key) {
				return false; // 找到了目标节点，返回节点信息
			}

			if (treeData[i].children && treeData[i].children.length > 0) {
				const result = getTreeById(treeData[i].children, key); // 递归查找
				if (!result) {
					return false; // 如果在子节点中找到了目标节点，返回结果
				}
			}
		}

		return key; // 遍历完当前节点和子节点都没有找到目标节点，返回null
	};

	return delNotIdArry();
};

const getNoticeInfo = async (): Promise<void> => {
	formLoading.value = true;
	let res: TsRes = await AlarmNoticeAPI.noticeGetById(editId);
	const data = res.data;
	formData.name = data.name;
	formData.type = data.type;
	formData.aiIdList = data.aiIdList;
	formData.alarmTypeList = data.alarmTypeList;
	formData.notifyTypeStr = data.notifyTypeStr;
	deviceIdList.value = data.deviceIdList;
	formData.deviceIdList = data.deviceIdList;
	formData.boxSerialList = !data.boxSerialList ? undefined : data.boxSerialList;
	formData.deviceList = !data.deviceList ? undefined : delNoArray(boxDeviceList.value, data.deviceList);
	formData.notifyPersonList = data.notifyPersonList;
	formData.id = data.id;
	formLoading.value = false;
	formData.areaItem = { label: res.data.areaName, value: res.data.areaId };
	formData.notifyTypeStr = data.notifyTypeStr;
	formData.personIdList = formData.notifyPersonList.map((i: any) => i.areapersonId);
};

const watchEffectStop = watchEffect(() => {
	if (formData.name) {
		formData.name = formData.name.replace(/\s+/, '');
	}

	if (formData.notifyPersonList.map((v: any) => v.userName)) {
		for (let i = 0; i < formData.notifyPersonList.length; i++) {
			formData.notifyPersonList[i].userName = formData.notifyPersonList[i].userName.replace(/\s+/, '');
		}
	}
});
onUnmounted(() => {
	watchEffectStop();
});

onMounted(async () => {
	getAllRegions();
	getPersonList('');

	await getBoxDeviceList();

	getDeviceAreaList();

	if (route.query.id) {
		await getNoticeInfo();
		getAIServiceList();
	}
});
</script>

<style lang="less">
.alarm-notification-form-container {
	.icon-close-circle-fill {
		color: @text03 !important;
	}

	.ant-input-affix-wrapper {
		border: 1px solid #2b3a50;
		background: transparent !important;
	}

	.title {
		display: flex;
		font-size: 20px;
		font-weight: 700;
		font-style: normal;
		line-height: 28px; /* 140% */
		align-items: center;
		color: @text01;
	}

	.ant-form {
		.ant-form-item {
			.ant-form-item-label {
				margin-top: 32px;
			}
		}
	}

	.the-common-title {
		display: flex;
		margin-bottom: 16px;
		color: @text01;
		align-items: center;
	}

	.the-alarm-notice-config {
		margin: 0 auto 20px;

		.the-alarm-notice-form {
			width: 555px;
			border: @borderColor01;
			border-radius: 4px;
			padding: 20px 20px 40px;
			background: @background02;
			box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);

			.form-button {
				margin-right: 8px;
			}

			.ant-checkbox-wrapper {
				margin-right: 16px;
				color: @text01;
			}

			.addBtn {
				font-size: 14px;
				font-weight: 400;
				line-height: 22px; /* 157.143% */
				color: @link01;
				cursor: pointer;

				&:hover {
					color: #679ff6;
					opacity: 0.85;
					cursor: pointer;
				}

				&:active {
					color: #2f6bcb;
					cursor: pointer;
				}
			}

			.ant-space {
				margin-bottom: 20px;
			}
		}
	}

	.server-information {
		width: 360px;
		height: 368px;
		margin: 40px 0 0 80px;

		.title {
			display: flex;
		}

		.server-info {
			height: 328px;
			border: 1px solid @borderColor02;
			border-radius: 4px;
			padding: 12px 20px;
			background: #101b2f;
			box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);

			.server-item {
				border-bottom: 1px solid @borderColor02;
				padding: 12px 0;
				line-height: 22px;

				.label {
					margin-bottom: 8px;
					line-height: 22px;
					color: @text03;
				}

				.value {
					color: @text01;
				}
			}

			.server-item:last-child {
				border-bottom: none;
			}
		}
	}

	.tree-node-title {
		background: transparent !important;

		&:active {
			background: transparent !important;
		}
	}
}

:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected,
:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-checkbox + span.ant-tree-node-selected {
	background-color: @background01 !important;
}
</style>
